package net.huashitong.oversee.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.oversee.entity.GradePoint;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.entity.TackTaskLog;
import net.huashitong.oversee.filter.CoordinateFilter;
import net.huashitong.oversee.filter.GradePointFilter;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.filter.TackTaskLogFilter;
import net.huashitong.oversee.service.GradePointService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.oversee.service.TackTaskLogService;
import net.huashitong.taskGroup.entity.JobGroup;
import net.huashitong.user.databean.BnpUserDatabean;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.filter.OnlineFilter;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.utils.UtilsTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 攻坚控制器
 */
@Controller
@RequestMapping("/taskToTack")
public class TaskToTackCtrl extends JsonBaseController {
    @Override
    protected String getView(String s) {
        return "/modules/taskToTack/" + s;
    }

    @Autowired
    private SupervisionTaskService supervisionTaskService;
    @Autowired
    private TackTaskLogService tackTaskLogService;
    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private BnpUserService bnpUserService;
    @Autowired
    private GradePointService gradePointService;

    @RequestMapping(method = RequestMethod.GET)
    public String initPage(HttpServletRequest request, Model model) {
        model.addAttribute("leftType", "攻坚任务");

        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        //待办任务个数
        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
        model.addAttribute("nodeCount", nodeCount);
        model.addAttribute("user", bnpUser);

        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);

        //攻坚任务
        SupervisionTaskFilter taskFilter1 = new SupervisionTaskFilter();
        taskFilter1.setUserinfo(bnpUser.getPhone());
        taskFilter1.setBranchType(bnpUser.getBranchType());
        taskFilter1.setRole(bnpUser.getRole());
        taskFilter1.setValid("1");
        taskFilter1.setTackFlag("1");
        int myTackTaskNum = supervisionTaskService.getMissinTaskCount(taskFilter1);
        WebUtils.setSessionAttribute(request, "myTackTaskNum", myTackTaskNum);
        model.addAttribute("myTackTaskNum", myTackTaskNum);
        return getView("query");
    }

    //初始化数据
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute SupervisionTaskFilter filter, HttpServletRequest request, Model model) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        filter.setUserinfo(bnpUser.getPhone());
        filter.setBranchType(bnpUser.getBranchType());
        filter.setRole(bnpUser.getRole());
        if (StringUtils.isBlank(filter.getGroupId())) {
            filter.setGroupId(bnpUser.getGroupCode());
        }
        if (StringUtils.isBlank(filter.getTackFlag())) {
            filter.setTackFlag("1");
        }

        List<SupervisionTask> resList = supervisionTaskService.getTaskLists(filter);
        return coverJqGrid(filter, resList);
    }

    @RequestMapping("/filter")
    public String filter(@ModelAttribute SupervisionTaskFilter filter) {
        return getView("filter");
    }


    /**
     * 手动新建任务
     *
     * @param model
     * @return url
     */
    @RequestMapping(value = "/feedbackToTack", method = RequestMethod.GET)
    public String feedbackToTack(@ModelAttribute SupervisionTaskFilter filter, Model model) {
        return getView("feedbackToTack");
    }


    /**
     * 添加攻坚反馈
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/addTackLog/{id}", method = RequestMethod.GET)
    public String addTackLog(Model model, @PathVariable String id) {
        SupervisionTask task = supervisionTaskService.getById(id);
        String projectDetail = task.getTaskName() + ",目前已经逾期" +
                task.getOverdueDays() + "天,正处于第" + task.getTasktimes() + "轮督查任务，已转批成攻坚任务。";
        model.addAttribute("task", task);
        model.addAttribute("projectDetail", projectDetail);
        return getView("addTackLog");
    }

    @ResponseBody
    @RequestMapping(value = "/addTackLog", method = RequestMethod.POST)
    public Message addProblem(@ModelAttribute TackTaskLogFilter filter, HttpServletRequest request, Model model) {
        String taskId = filter.getSysId();
        SupervisionTask task = supervisionTaskService.getById(taskId);
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        TackTaskLog log = new TackTaskLog();
        log.setRecord(filter.getRecord());
        log.setNodeSysId(task.getNodeSysId());
        log.setTaskId(taskId);
        if (ObjectUtils.isNotBlank(bnpUser)) {
            log.setRecordPerson(bnpUser.getName());
            log.setRecordPersonSysId(bnpUser.getSysId());
        }
        if (StringUtils.isNotBlank(filter.getTaxproof())) {
            log.setTaxproof(filter.getTaxproof());
        }
        tackTaskLogService.save(log);
        return coverMessage("200");
    }


    /**
     * 查看攻坚过程日志
     *
     * @param model
     * @return url
     */
    @RequestMapping(value = "/readLog/{id}", method = RequestMethod.GET)
    public String readLog(Model model, HttpServletRequest request, @PathVariable String id) {
        SupervisionTask task = supervisionTaskService.getById(id);
        List<TackTaskLog> logs = tackTaskLogService.queryTackLogByTaskId(id);
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        String tackFlag = task.getTackFlag();
        if ("2".equals(tackFlag)) {
            //办结，需要办结时间
            String finishTackDate = "";
            if (logs.size() > 0) {
                if (StringUtils.isNotBlank(task.getFinishTackDate())) {
                    finishTackDate = task.getFinishTackDate();
                } else {
                    finishTackDate = logs.get(0).getCreateDate().replace("-", "");
                }
                model.addAttribute("finishTackDate", finishTackDate);
            }
        }
        model.addAttribute("task", task);
        model.addAttribute("logs", logs);
        model.addAttribute("bnpUser", bnpUser);
        return getView("tackTaskLog");
    }

//    /**
//     *  办结攻坚任务
//     * @return
//     */
//    @RequestMapping(value = "/finishTack/{id}", method = RequestMethod.GET)
//    public String finishTack(Model model, HttpServletRequest request, @PathVariable String id) {
//        SupervisionTask task = supervisionTaskService.getById(id);
//        String projectDetail = task.getTaskName() + ",目前已经逾期" +
//                task.getOverdueDays() + "天,正处于第" + task.getTasktimes() + "轮督查任务，已转批成攻坚任务。";
//        model.addAttribute("task", task);
//        model.addAttribute("projectDetail", projectDetail);
//        return getView("finishTack");
//    }

    @ResponseBody
    @RequestMapping(value = "/finishTack", method = RequestMethod.POST)
    public Message finishTack(@ModelAttribute SupervisionTaskFilter filter, HttpServletRequest request, Model model) {
        String taskId = filter.getSysId();
        SupervisionTask task = supervisionTaskService.getById(taskId);
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        TackTaskLog log = new TackTaskLog();
        log.setRecord(filter.getRecord());
        log.setNodeSysId(task.getNodeSysId());
        log.setTaskId(taskId);
        if (ObjectUtils.isNotBlank(bnpUser)) {
            log.setRecordPerson(bnpUser.getName());
            log.setRecordPersonSysId(bnpUser.getSysId());
        }
        if (StringUtils.isNotBlank(filter.getTaxproof())) {
            log.setTaxproof(filter.getTaxproof());
        }
        tackTaskLogService.save(log);

        if (StringUtils.isNotBlank(filter.getTackFlag())) {
            task.setTackFlag(filter.getTackFlag());
        }
        supervisionTaskService.update(task);
        return coverMessage("200");
    }


    /**
     * 审核攻坚
     *
     * @return
     */
    @RequestMapping(value = "/approval/{id}", method = RequestMethod.GET)
    public String approval(Model model, HttpServletRequest request, @PathVariable String id) {
        SupervisionTask task = supervisionTaskService.getById(id);
        String projectDetail = task.getTaskName() + ",目前已经逾期" +
                task.getOverdueDays() + "天,正处于第" + task.getTasktimes() + "轮督查任务，已转批成攻坚任务。";
        List<TackTaskLog> logs = tackTaskLogService.queryTackLogByTaskId(id);
        String tackFlag = task.getTackFlag();
        if ("2".equals(tackFlag)) {
            //办结，需要办结时间
            String finishTackDate = "";
            if (logs.size() > 0) {
                if (StringUtils.isNotBlank(task.getFinishTackDate())) {
                    finishTackDate = task.getFinishTackDate();
                } else {
                    finishTackDate = logs.get(0).getCreateDate().replace("-", "");
                }
                model.addAttribute("finishTackDate", finishTackDate);
            }
        }
        model.addAttribute("task", task);
        model.addAttribute("projectDetail", projectDetail);
        model.addAttribute("task", task);
        return getView("approval");
    }

    @ResponseBody
    @RequestMapping(value = "/approval", method = RequestMethod.POST)
    public Message approval(@ModelAttribute SupervisionTaskFilter filter, HttpServletRequest request, Model model) throws ParseException {
        String taskId = filter.getSysId();
        SupervisionTask task = supervisionTaskService.getById(taskId);
        if (StringUtils.isNotBlank(filter.getTackFlag())) {
            task.setTackFlag(filter.getTackFlag());

            //查询分管领导
            String projectId = task.getProjectId();
            NewProjects project = newProjectsService.getById(projectId);
            String resUser = project.getResUser();          //分管领导
            String resPhone = project.getResPhone();        //分管领导手机号
            BnpUser fenguanUser = bnpUserService.getBnpUserByPhoneAndName(resPhone, resUser);
            String fenguanUserId = "null";
            String fenguanUserName = "null";
            String fenguanUserBranch = "null";
            if(ObjectUtils.isNotBlank(fenguanUser)){
                fenguanUserId = fenguanUser.getSysId();
                fenguanUserName = fenguanUser.getName();
                fenguanUserBranch = fenguanUser.getBranch();
            }

            //审核通过
            if ("3".equals(filter.getTackFlag())) {
                //攻坚完成  督查结果设置--1
                task.setTaskResult("1");
                task.setRespResult("1");
                task.setSupervisionResult("1");
                //攻坚完成设置实际完成时间
                task.setEndDate(filter.getFinishTackDate());
                //保存办结时间到任务表里面
                task.setFinishTackDate(filter.getFinishTackDate());
                //保存审核时间到任务表里面
                task.setApprovalTackDate(UtilsTools.getCurrentDate());
                task.setApprovalTackText(filter.getApprovalTackText());
                //设置及时完成率
                Date EndDate = UtilsTools.StringToDate(task.getPlanEndDate());  //计划完成时间
                Date currentDate = UtilsTools.StringToDate(task.getEndDate());  //办结时间（实际完成时间）
                int flag = EndDate.compareTo(currentDate); //计划结束时间和当前时间比较。是否到期。

                //审核通过将得分记录到绩效得分表里面去(考核分管领导)
                GradePoint gradePoint = new GradePoint();
                gradePoint.setCheckObjectId(fenguanUserId);
                gradePoint.setCheckObject(fenguanUserName);
                gradePoint.setTaskName(task.getTaskName());
                gradePoint.setTaskId(task.getSysId());
                gradePoint.setTaskContent(task.getTaskContent());
                gradePoint.setResDept(fenguanUserBranch);
                gradePoint.setCheckType("攻坚任务");
                if (flag == 0) {
                    //计划结束当天完成
                    task.setTackPercent("80.0");
                    gradePoint.setSoucre("10.0");
                } else if (flag < 0) {
                    //超时完成
                    task.setTackPercent("60.0");
                    gradePoint.setSoucre("10.0");
                } else {
                    //计划时间完成
                    task.setTackPercent("100.0");
                    gradePoint.setSoucre("10.0");
                }
                gradePointService.save(gradePoint);
            }else{
                GradePoint gradePoint = new GradePoint();
                gradePoint.setCheckObjectId(fenguanUserId);
                gradePoint.setCheckObject(fenguanUserName);
                gradePoint.setTaskName(task.getTaskName());
                gradePoint.setTaskId(task.getSysId());
                gradePoint.setTaskContent(task.getTaskContent());
                gradePoint.setResDept(fenguanUserBranch);
                gradePoint.setCheckType("攻坚任务");
                gradePoint.setSoucre("0.0");
                gradePointService.save(gradePoint);
            }
        }
        supervisionTaskService.update(task);
        return coverMessage("200");
    }

    /**
     * 获取各攻坚阶段的数目
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getTackTaskEachNums")
    public Message getTackTaskEachNums(HttpServletRequest request) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        Map<String, Integer> integerMap = supervisionTaskService.getTackTaskEachNums(bnpUser);
        return coverMessage("200", "查询成功", integerMap);
    }
}
